package com.ch.engine.utils.aes2;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @author yhs
 * @Description:
 * @creatDate 2022/7/13 15:24
 */
public class ASEUtils {

    public static String encrypt(String algorithm, String input, SecretKey key,
                                 IvParameterSpec iv) throws NoSuchPaddingException, NoSuchAlgorithmException,
            InvalidAlgorithmParameterException, InvalidKeyException,
            BadPaddingException, IllegalBlockSizeException {

        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
        byte[] cipherText = cipher.doFinal(input.getBytes());
        return Base64.getEncoder().encodeToString(cipherText);

    }

    public static String decrypt(String algorithm, String cipherText, SecretKey key,
                                 IvParameterSpec iv) throws NoSuchPaddingException, NoSuchAlgorithmException,
            InvalidAlgorithmParameterException, InvalidKeyException,
            BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] plainText = cipher.doFinal(Base64.getDecoder()
                .decode(cipherText));
        return new String(plainText);
    }

    public static IvParameterSpec generateIv() {
        byte[] iv = new byte[16];
        new SecureRandom().nextBytes(iv);
        return new IvParameterSpec(iv);
    }

    public static SecretKey generateKey(int n) throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(n);
        SecretKey key = keyGenerator.generateKey();
        String algorithm = key.getAlgorithm();
        System.out.println(algorithm);
        return key;
    }


    public static void main(String[] args) {
        try {
            String input = "baeldung";
            SecretKey key = generateKey(128);
            IvParameterSpec ivParameterSpec = generateIv();
            // System.out.println(new String(ivParameterSpec.getIV()));
            String algorithm = "AES/CBC/PKCS5Padding";
            String cipherText = encrypt(algorithm, input, key, ivParameterSpec);
            String plainText = decrypt(algorithm, cipherText, key, ivParameterSpec);
            System.out.println(cipherText);
            System.out.println(plainText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}